package me.ezitku.base.extensions

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.fragment.app.Fragment
import com.pawegio.kandroid.activityManager


/**
 * Created by yurqi on 2017/6/26.
 */

/**
 * نۆۋەتتىكى ئەپ ئالدى سۇپىدا ئىجرا بولىۋاتامدۇ؟
 */
 fun Context.thisAppIsRunForeground(): Boolean {
        val processes = activityManager!!.runningAppProcesses
        for (processInfo in processes) {
            if (processInfo.processName == packageName) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true
                }
            }
        }
    return false
}

/**
 * نۆۋەتتىكى ئەپ كەينى سۇپىدا ئىجرا بولىۋاتامدۇ
 * ئاندرويىد 5.0 دىن كېيىن نورمال ئىشلىشى مۇمكىن
 * سىناق قىلىنمىغان كود
 * @return true بولسا كەينى سۇپىدا, false بولسا ئالدىدا
 */
fun Context.thisAppIsRunBackground(): Boolean {
    var isInBackground = true
    val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        val runningProcesses = am.runningAppProcesses
        for (processInfo in runningProcesses) {
            //前台程序
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (activeProcess in processInfo.pkgList) {
                    if (activeProcess == packageName) {
                        isInBackground = false
                    }
                }
            }
        }
    } else {
        val taskInfo = am.getRunningTasks(1)
        val componentInfo = taskInfo[0].topActivity
        if (componentInfo.packageName == packageName) {
            isInBackground = false
        }
    }

    return isInBackground
}


/**
 * نۆۋەتتىكى ئەپنىڭ باشقۇرۇش رايۇنىنى قوزغىتىش
 */
fun Context.startThisAppSettings() {
    var intent = Intent()
    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    var uri = Uri.fromParts("package", packageName, null)
    intent.data = uri
    startActivity(intent)
}

/**
 * "تېلفۇن ئۇرۇش كۆزنىكىگە ئۆتكۈزۈش"
 */
fun Context.startCall(msg:String){
    val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + msg))
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    startActivity(intent)
}

fun Fragment.startCall(msg:String){
    activity!!.startCall(msg)
}

/**
 *此应用是否开发中(测试中)
 */
fun Context.thisAppIsDebugging():Boolean{
    return try {
        val info = applicationInfo
        info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
    } catch (e:Exception) {
        false
    }
}

